﻿
@{
    var isEmbed = Context?.Request?.Query["embed"].ToString() == "1";
    Layout = isEmbed ? null : "_Layout";
}

<link href="~/css/site.css" rel="stylesheet" />
<link href="~/layui/css/layui.css" rel="stylesheet" />
<script src="~/js/site.js"></script>
<script src="~/layui/layui.js"></script>
<script src="~/js.cookie.js"></script>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>


@* <button type="button" class="layui-btn layui-btn-primary" lay-on="test-page">工序分类添加</button> *@
<button type="button" class="layui-btn" onclick="openDialog('add')">工序分类添加</button>
<table class="layui-table">
    <thead>
        <tr>
            <th>工序分类编号</th>
            <th>工序分类名称</th>
            <th>状态</th>
            <th>备注</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody id="tb"></tbody>
</table>
<div id="demo-laypage-all"></div>

<script>
    //加载事件
    $(function(){
        shows()
    })
    var PageIndex=1;
    var PageSize=5;
    var TotalCount=0;
    var TotalPages=0;
    //获取工序分类列表
    function shows(){

        $.ajax({
            url: 'http://localhost:5161/api/Process/ProcessTypeQuery?PageIndex='+PageIndex+'&PageSize='+PageSize,
            dataType:'json',
            type:'get',
            contentType:'application/json',
            async:false,
            success:res=>{
                
                console.log(res);
                $("#tb").empty();
                TotalCount=res.data.totalCount
                TotalPages=res.data.totalPages
                
                // 重新渲染分页组件
                reloadPage();
                
                $(res.data.list).empty().each(function(){
                    if(this.ptStatus==false){
                        this.ptStatus="启用"
                    }else{
                        this.ptStatus="禁用"
                    }
                    // 兼容不同的主键字段名，依次尝试
                    var itemId = this.id || this.ptId || this.ptID || this.processTypeId || this.ProcessTypeId || '';

                    $("#tb").append(`
                       <tr>
                        <th>${this.ptCode}</th>
                        <th>${this.ptName}</th>
                        <th>${this.ptStatus}</th>
                        <th>${this.note}</th>
                        <th>
                            <button class="layui-btn layui-btn-primary layui-border-purple" data-id="${itemId}" data-ptcode="${this.ptCode}" data-ptname="${this.ptName}" data-ptstatus="${this.ptStatus}" data-note="${this.note || ''}" onclick="openDialogFromRow(this)">编辑</button>
                            <button class="layui-btn layui-btn-primary layui-border-red" data-id="${itemId}" data-ptcode="${this.ptCode}" data-ptname="${this.ptName}" onclick="deleteProcessType(this)">删除</button>
                        <th>
                       </tr>
                    `)
                })
            }
        })
    }

    function reloadPage(){
         //分页
    layui.use(function(){
      var laypage = layui.laypage;
      // 完整显示
      laypage.render({
        elem: 'demo-laypage-all', // 元素 id
        count: TotalCount, // 数据总数
        limit:PageSize,
        curr: PageIndex,
        limits: [5, 10, 15, 20],
        layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'], // 功能布局
        jump: function(obj, first){
          if (!first) {
            PageIndex = obj.curr;
            PageSize = obj.limit;
            shows();
          }
        }
      });
    });
    }

    


    // 统一的新增/编辑对话框
    var dialogMode = 'add'; // 'add' | 'edit'
    var originalPtCode = '';
    var editId = '';
    layui.use(function(){
      var $ = layui.$;
      window.layuiLayer = layui.layer;
    });

    function openDialogFromRow(btn){
        var $btn = $(btn);
        var preset = {
            id: $btn.data('id'),
            ptCode: $btn.data('ptcode'),
            ptName: $btn.data('ptname'),
            ptStatus: $btn.data('ptstatus'),
            note: $btn.data('note')
        };
        openDialog('edit', preset);
    }
    //添加、修改对话框
    function openDialog(mode, preset){
        dialogMode = mode || 'add';
        originalPtCode = preset && preset.ptCode ? preset.ptCode : '';
        editId = preset && preset.id ? preset.id : '';
        var isEdit = dialogMode === 'edit';
        var statusEnabled = 'false';
        if(preset && preset.ptStatus){
            statusEnabled = (preset.ptStatus === '禁用') ? 'true' : 'false';
        }
        var titleText = isEdit ? '工序分类编辑' : '工序分类添加';
        layuiLayer.open({
            type: 1,
            title: titleText,
            area: ['600px', '600px'],
            content:  `<div style="padding: 16px;">
                   <table class="layui-table">
                    <tr>
                        <th>工序分类编号</th>
                        <th>
                            <input type="text" placeholder="工序分类编号" class="layui-input" id="PTCode" value="${isEdit ? (preset.ptCode||'') : ''}">
                        </th>
                    </tr>
                    <tr>
                        <th>工序分类名称</th>
                        <th>
                            <input type="text" placeholder="工序分类名称" class="layui-input" id="PTName" value="${isEdit ? (preset.ptName||'') : ''}">
                        </th>
                    </tr>
                    <tr>
                        <th>状态</th>
                        <th>
                            <label style="margin-right:12px;"><input type="radio" name="AAA" value="false" ${statusEnabled==='false'?'checked':''}> 启用</label>
                            <label><input type="radio" name="AAA" value="true" ${statusEnabled==='true'?'checked':''}> 禁用</label>
                        </th>
                    </tr>
                    <tr>
                        <th>备注</th>
                        <th>
                            <textarea placeholder="" class="layui-textarea" id="Note">${isEdit ? (preset.note||'') : ''}</textarea>
                        </th>
                    </tr>
                    <tr>
                        <th></th>
                        <th>
                            <button type="button" class="layui-btn" onclick="saveProcessType()">${isEdit ? '保存修改' : '保存'}</button>
                        </th>
                    </tr>
                </table>
            </div>`
        });
    }

    // 统一保存（添加/编辑）
    function saveProcessType(){
        var ptCode=$("#PTCode").val();
        var ptName=$("#PTName").val();
        var ptStatus=$('input:radio:checked').val();
        var note=$("#Note").val();
        var data={
            "ptCode":ptCode,
            "ptName":ptName,
            "ptStatus":JSON.parse(ptStatus),
            "note":note
        }
        console.log(data);
        if(ptCode==""||ptName==""){
            layer.msg("工序分类编号和工序分类名称不能为空",{icon:7})
            return
        }
        var url = 'http://localhost:5161/api/Process/ProcessTypeAdd';
        var method = 'post';
        if(dialogMode === 'edit'){
            // 如后端需要原始编号，可一并提交
            data.originalPtCode = originalPtCode || ptCode;
            if(editId){ data.id = editId; }
            data.IsUpdOrDel = false;  // false表示修改操作
            url = 'http://localhost:5161/api/Process/ProcessTypeEdit';
            method = 'post';
        }
        $.ajax({
            url: url,
            dataType:'json',
            type:method,
            contentType:'application/json',
            data:JSON.stringify(data),
            async:false,
            success:res=>{
                console.log(res);
                if(res.code==200){
                    layer.msg(dialogMode==='edit'?"修改成功":"添加成功")
                    shows()
                }else{
                    layer.msg(res.message)
                }
            }        
        })
    }

    //删除
    function deleteProcessType(btn){
        var $btn = $(btn);
        var itemId = $btn.data('id');
        var ptCode = $btn.data('ptcode');
        var ptName = $btn.data('ptname');
        
        // 确认删除对话框
        layuiLayer.confirm(
            `确定要删除工序分类"${ptName}"(${ptCode})"吗？`, 
            {
                title: '确认删除',
                btn: ['确定删除', '取消'],
                icon: 3
            }, 
            function(index){
                // 用户确认删除
                var data = {
                    "id": itemId,
                    "ptCode": ptCode,
                    "ptName": ptName,
                    "ptStatus": false,
                    "note": "",
                    "IsUpdOrDel": true  // true表示删除操作
                };
                
                $.ajax({
                    url: 'http://localhost:5161/api/Process/ProcessTypeEdit',
                    dataType: 'json',
                    type: 'post',
                    contentType: 'application/json',
                    data: JSON.stringify(data),
                    async: false,
                    success: function(res){
                        console.log(res);
                        if(res.code == 200){
                            layuiLayer.msg("删除成功", {icon: 1});
                            
                            // 如果当前页没有数据了，跳转到上一页
                            if (PageIndex > 1 && TotalCount <= (PageIndex - 1) * PageSize) {
                                PageIndex--;
                            }
                            
                            shows(); // 刷新列表
                        } else {
                            layuiLayer.msg(res.message || "删除失败", {icon: 2});
                        }
                    },
                    error: function(){
                        layuiLayer.msg("删除失败，请稍后重试", {icon: 2});
                    }
                });
                
                layuiLayer.close(index);
            }
        );
    }


    

</script>